/**
 * 
 */
package kr.pe.johnkim.dayve.rest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import kr.pe.johnkim.dayve.provider.DayveMember;
import kr.pe.johnkim.dayve.util.ExternalJoinConstant;

import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

/**
 * 멤버 RESTful 관련 메소드들을 구현하는 클래스 이다.
 * 
 * @author johnkim
 *
 */
public class DayveMemberRest {

	public static final String TAG = DayveMemberRest.class.getSimpleName();
	
	// 서버 주소.
	public static final String SERVER_URL = ExternalJoinConstant.MOBILE_SERVER_URL;
	
	// 멤버관련 기능 컨트롤러 매핑.
	public static final String MYHISTORY_MEMBER_CONTROLLER = "/myHistoryMemberController";
	
	// 멤버 등록 중복 검사를 한다.
	public static final String MYHISTORY_MEMBER_CHECK_DUPLICATION = "/checkDuplication";
	
	// 멤버를 등록 한다.
	public static final String MYHISTORY_MEMBER_REGISTER = "/registerMember";
	
	// server 로그인을 한다.
	public static final String MYHISTORY_MEMBER_LOGIN = "/login";
	
	// 사용자의 마일리지를 가져 온다.
	public static final String MYHISTORY_MILEAGE = "/selectMileage";
	
	// 마일리지를 추가 한다.
	public static final String MYHISTORY_MILEAGE_INCREASE = "/updateMileage";
	
	// 사용자 비밀번호를 변경 한다.
	public static final String MYHISTORY_CHANGE_PASSWORD = "/updatePassword";
	
	// 사용자 이메일을 변경 한다.
	public static final String MYHISTORY_CHANGE_EMAIL = "/updateEmail";
	
	/**
	 * 사용자 등록 시 id 중복 검사를 한다.
	 * 
	 * 등록되어 있는 id 의 갯수를 가져 온다.
	 * 
	 * 1. 사용할 수 있는 id     : 0
	 * 2. 이미 등록되어 있는 id : 1
	 * 3. 실행 중 오류 발생     : ERROR
	 * 
	 * @param dayveMember
	 * @return 0 or 1 or ERROR
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveMember checkDuplication(DayveMember dayveMember) throws JSONException, IOException {
		Log.i(TAG,  "checkDuplication");
		
		JSONObject jsonMember = new JSONObject();
		
		jsonMember.put("id", dayveMember.getId());
		jsonMember.put("activateYn", dayveMember.getActivateYn());
		
		String jsonString = "{\"myHistoryMember\":" + jsonMember.toString() + "}";
		
		Log.i(TAG, "jsonMember : " + jsonString);
		
		DayveMember mDayveMember = new DayveMember();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_MEMBER_CONTROLLER + MYHISTORY_MEMBER_CHECK_DUPLICATION);
//			URL postUrl = new URL(SERVER_URL + MYHISTORY_MEMBER_CHECK_DUPLICATION);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonMember = new JSONObject(line);
	            	JSONObject mJsonMember2 = mJsonMember.getJSONObject("myHistoryMember");
	            	
	            	mDayveMember.setCount(mJsonMember2.getString("count"));
	        	}
	        }
	        
	        Log.i(TAG, "Success to checkDuplication Member.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to checkDuplication Member.");
			mDayveMember.setCount("ERROR");
		}
		
		return mDayveMember;
	}
	
	/**
	 * 사용자를 등록 한다.
	 * 
	 * 등록 결과는 DayveMember 도메인 클래스의 result(SUCCESS or FAIL) 에 담아서
	 * 반환 한다.
	 * 
	 * @param dayveMember
	 * @return SUCCESS or FAIL
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveMember registerMember(DayveMember dayveMember) throws JSONException, IOException {
		Log.i(TAG,  "registerMember");
		
		JSONObject jsonMember = new JSONObject();
		
		jsonMember.put("id", dayveMember.getId());
		jsonMember.put("password", dayveMember.getPassword());
		jsonMember.put("email", dayveMember.getEmail());
		jsonMember.put("openEmailYn", dayveMember.getOpenEmailYn());
		jsonMember.put("mobilePhoneNumber", dayveMember.getMobilePhoneNumber());
		jsonMember.put("openMobilePhoneYn", dayveMember.getOpenMobilePhoneYn());
		jsonMember.put("country", dayveMember.getCountry());
		jsonMember.put("openCountryYn", dayveMember.getOpenCountryYn());
		jsonMember.put("homePage", dayveMember.getHomePage());
		jsonMember.put("openHomePageYn", dayveMember.getOpenHomePageYn());
		jsonMember.put("nickName", dayveMember.getNickName());
		jsonMember.put("openNickNameYn", dayveMember.getOpenNickNameYn());
		jsonMember.put("profileImageUrl", dayveMember.getProfileImageUrl());
		jsonMember.put("openProfileImageYn", dayveMember.getOpenProfileImageYn());
		jsonMember.put("facebookId", dayveMember.getFacebookId());
		jsonMember.put("facebookPassword", dayveMember.getFacebookPassword());
		jsonMember.put("openFacebookYn", dayveMember.getOpenFacebookYn());
		jsonMember.put("twitterId", dayveMember.getTwitterId());
		jsonMember.put("twitterPassword", dayveMember.getTwitterPassword());
		jsonMember.put("openTwitterYn", dayveMember.getOpenTwitterYn());
		jsonMember.put("birthday", dayveMember.getBirthday());
		jsonMember.put("sex", dayveMember.getSex());
		jsonMember.put("mileage", dayveMember.getMileage());
		jsonMember.put("level", dayveMember.getLevel());
		jsonMember.put("activateYn", dayveMember.getActivateYn());
		jsonMember.put("modifyDate", dayveMember.getModifyDate());
		jsonMember.put("registerDate", dayveMember.getRegisterDate());
		
		String jsonString = "{\"myHistoryMember\":" + jsonMember.toString() + "}";
		
		Log.i(TAG, "jsonMember : " + jsonString);
		
		DayveMember mDayveMember = new DayveMember();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_MEMBER_CONTROLLER + MYHISTORY_MEMBER_REGISTER);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonMember = new JSONObject(line);
	            	JSONObject mJsonMember2 = mJsonMember.getJSONObject("myHistoryMember");
	            	
	            	mDayveMember.setResult(mJsonMember2.getString("result"));
	        	}
	        }
	        
	        Log.i(TAG, "Success to register Member.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to register Member.");
		}
		
		return mDayveMember;
	}
	
	/**
	 * server 로그인을 한다.
	 * 
	 * 1. id, password 가 일치 함       : 1
	 * 2. id, password 가 일치하지 않음 : 0
	 * 3. 실행 중 오류 발생             : ERROR
	 * 
	 * @param dayveMember
	 * @return 1 or 0 or ERROR
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveMember login(DayveMember dayveMember) throws JSONException, IOException {
		Log.i(TAG, "login");
		
		JSONObject jsonMember = new JSONObject();
		
		jsonMember.put("id", dayveMember.getId());
		jsonMember.put("password", dayveMember.getPassword());
		
		String jsonString = "{\"myHistoryMember\":" + jsonMember.toString() + "}";
		
		Log.i(TAG, "jsonMember : " + jsonString);
		
		DayveMember mDayveMember = new DayveMember();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_MEMBER_CONTROLLER + MYHISTORY_MEMBER_LOGIN);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonMember = new JSONObject(line);
	            	JSONObject mJsonMember2 = mJsonMember.getJSONObject("myHistoryMember");
	            	
	            	mDayveMember.setCount(mJsonMember2.getString("count"));
	        	}
	        }
	        
	        Log.e(TAG, "Success to login.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to login.");
			mDayveMember.setCount("ERROR");
		}
		
		return mDayveMember;
	}
	
	/**
	 * 사용자의 마일리지 점수를 가져 온다.
	 * 
	 * @param dayveMember
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveMember selectMileage(DayveMember dayveMember) throws JSONException, IOException {
		Log.i(TAG, "selectMileage");
		
		JSONObject jsonMember = new JSONObject();
		
		jsonMember.put("id", dayveMember.getId());
		
		String jsonString = "{\"myHistoryMember\":" + jsonMember.toString() + "}";
		
		Log.i(TAG, "jsonMember : " + jsonString);
		
		DayveMember mDayveMember = new DayveMember();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_MEMBER_CONTROLLER + MYHISTORY_MILEAGE);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonMember = new JSONObject(line);
	            	JSONObject mJsonMember2 = mJsonMember.getJSONObject("myHistoryMember");
	            	
	            	mDayveMember.setMileage(mJsonMember2.getString("mileage"));
	            	
	            	Log.i(TAG, "Success to select mileage.");
	        	}
	        }
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to select mileage.");
		}
		
		return mDayveMember;
	}
	
	/**
	 * 마일리지 점수를 추가 한다.
	 * 
	 * @param dayveMember
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveMember updateMileage(DayveMember dayveMember) throws JSONException, IOException {
		Log.i(TAG, "updateMileage");
		
		JSONObject jsonMember = new JSONObject();
		
		jsonMember.put("id", dayveMember.getId());
		jsonMember.put("mileage", dayveMember.getMileage());
		jsonMember.put("modifyDate", dayveMember.getModifyDate());
		
		String jsonString = "{\"myHistoryMember\":" + jsonMember.toString() + "}";
		
		Log.i(TAG, "jsonMember : " + jsonString);
		
		DayveMember mDayveMember = new DayveMember();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_MEMBER_CONTROLLER + MYHISTORY_MILEAGE_INCREASE);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonMember = new JSONObject(line);
	            	JSONObject mJsonMember2 = mJsonMember.getJSONObject("myHistoryMember");
	            	
	            	mDayveMember.setResult(mJsonMember2.getString("result"));
	        	}
	        }
	        
	        Log.i(TAG, "Success to update mileage.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to update mileage.");
		}
		
		return mDayveMember;
	}
	
	/**
	 * 사용자 비밀번호를 변경 한다.
	 * 
	 * @param dayveMember
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveMember updatePassword(DayveMember dayveMember) throws JSONException, IOException {
		Log.i(TAG, "updatePassword");
		
		JSONObject jsonMember = new JSONObject();
		
		jsonMember.put("id", dayveMember.getId());
		jsonMember.put("password", dayveMember.getPassword());
		jsonMember.put("modifyDate", dayveMember.getModifyDate());
		
		String jsonString = "{\"myHistoryMember\":" + jsonMember.toString() + "}";
		
		Log.i(TAG, "jsonMember : " + jsonString);
		
		DayveMember mDayveMember = new DayveMember();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_MEMBER_CONTROLLER + MYHISTORY_CHANGE_PASSWORD);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonMember = new JSONObject(line);
	            	JSONObject mJsonMember2 = mJsonMember.getJSONObject("myHistoryMember");
	            	
	            	mDayveMember.setResult(mJsonMember2.getString("result"));
	            	
	            	Log.e(TAG, ">> result : " + mDayveMember.getResult());
	        	}
	        }
	        
	        Log.i(TAG, "Success to update password.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to update password.");
		}
		
		return mDayveMember;
	}
	
	/**
	 * 사용자 이메일을 변경 한다.
	 * 
	 * @param dayveMember
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveMember updateEmail(DayveMember dayveMember) throws JSONException, IOException {
		Log.i(TAG, "updateEmail");
		
		JSONObject jsonMember = new JSONObject();
		
		jsonMember.put("id", dayveMember.getId());
		jsonMember.put("email", dayveMember.getEmail());
		jsonMember.put("modifyDate", dayveMember.getModifyDate());
		
		String jsonString = "{\"myHistoryMember\":" + jsonMember.toString() + "}";
		
		Log.i(TAG, "jsonMember : " + jsonString);
		
		DayveMember mDayveMember = new DayveMember();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_MEMBER_CONTROLLER + MYHISTORY_CHANGE_EMAIL);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonMember = new JSONObject(line);
	            	JSONObject mJsonMember2 = mJsonMember.getJSONObject("myHistoryMember");
	            	
	            	mDayveMember.setResult(mJsonMember2.getString("result"));
	            	
	            	Log.e(TAG, ">> result : " + mDayveMember.getResult());
	        	}
	        }
	        
	        Log.i(TAG, "Success to update email.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to update email.");
		}
		
		return mDayveMember;
	}
}
